package org.sysmhg.base.web;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.sysmhg.base.model.Company;
import org.sysmhg.base.service.CompanyService;
import org.sysmhg.util.json.JSONArray;
import org.sysmhg.util.json.JSONObject;

public class CompanyController extends MultiActionController{
	
	@SuppressWarnings("unused")
	private CompanyService companyService;

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}
	
	@SuppressWarnings("unchecked")
	public void getCompanies(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.info("Entering to method getCompanies");
        PrintWriter out = null;
        JSONObject jsonObjectRoot = null;
        
        response.setContentType("text/plain");
		out = response.getWriter();
		
        jsonObjectRoot = new JSONObject();
        
        try {
        	List<Company> listCompanies =  companyService.getCompanies(null, null);			
        	JSONArray jsonArray = new JSONArray();
        	int i = 0;
        	for (Company company : listCompanies) {
        		JSONObject jsonObject = new JSONObject(company);
	    		jsonObject.put("rownum", ++i);
		    	jsonArray.put(jsonObject);	
			}
	    	jsonObjectRoot.put("data", jsonArray);	
    	}catch (Exception e) {
    		 logger.error(e);
    	}finally{
    		logger.info("Response from method getCompanies: " + jsonObjectRoot.toString());
    		out.print(jsonObjectRoot.toString());
    		out.flush();
	    	out.close();	        	        		        
    	}
	}
	
}
